package edu.mju.controller;

import com.alibaba.fastjson.JSONObject;
import edu.mju.entity.User;
import edu.mju.service.IUserService;
import edu.mju.service.impl.UserServiceImpl;
import edu.mju.util.Pager;
import edu.mju.util.RequestStrUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author:wyp
 * @Date:2020/5/24 11:53
 */
@WebServlet("/userController")
public class UserController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //统一编码，防止中文乱码
        req.setCharacterEncoding("UTF-8");
        //获取method
        String method = req.getParameter("method");

        System.out.println("doget:"+method);
        if("userList".equals(method)){
            //对应backindex.jsp的用户列表
            req.getRequestDispatcher("/WEB-INF/view/backindex/member-list.jsp").forward(req,resp);
        }else if("userEdit".equals(method)){
            String userId = req.getParameter("userId");
            req.getRequestDispatcher("/WEB-INF/view/backindex/member-edit.jsp?userId="+userId).forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //统一编码，防止中文乱码
        resp.setContentType("text/html;charSet=utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        //获取method
        String method = req.getParameter("method");
        System.out.println("dopost:"+method);
        if("userList".equals(method)){
            //对应member-list.jsp 的页面载入效果
            pagernate(req, resp);
        }else if("userGetByuserId".equals(method)){
            //对应member-edit.jsp 的页面载入效果
            userGetByuserId(req, resp);
        }else if("userUpdate".equals(method)) {
            //对应member-edit.jsp 的更新用户操作
            userUpdate(req, resp);
        }else if("userDelete".equals(method)){
            //对应member-list.jsp的删除操作
            userDelete(req,resp);
        }
    }
    /**
     * 执行更新
     * @param req
     * @param resp
     */
    private void userDelete(HttpServletRequest req, HttpServletResponse resp){
        //获取ajax传的参数
        Integer userId = RequestStrUtil.getValue(req.getParameter("userId"),0);

        IUserService userService = new UserServiceImpl();
        try {
            if(userService.delete(userId)){
                User user = new User();
                user.setUserId(userId);
                String rs = JSONObject.toJSONString(user);
                resp.getWriter().write(rs);
            }else {
                resp.getWriter().write(String.valueOf(false));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 执行更新
     * @param req
     * @param resp
     */
    private void userUpdate(HttpServletRequest req, HttpServletResponse resp){
        //获取ajax传的参数
        Integer userId = Integer.valueOf(req.getParameter("userId"));
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String userTel = req.getParameter("userTel");
        Byte userSex = Byte.valueOf((req.getParameter("userSex")));
        String userRole = req.getParameter("userRole");
        //用获取的参数创建User对象
        User user = new User(userId,userName,userPassword,userTel,userSex,userRole);
        IUserService userService = new UserServiceImpl();
        try {
            if(userService.backupdate(user)){
                String rs = JSONObject.toJSONString(user);
                resp.getWriter().write(rs);
            }else {
                resp.getWriter().write("false");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 返回根据用户ID查找的用户数据
     * @param req
     * @param resp
     */
    private void userGetByuserId(HttpServletRequest req, HttpServletResponse resp){
        Integer userId = Integer.valueOf(req.getParameter("userId"));
        IUserService service = new UserServiceImpl();
        User user =service.findByUserId(userId);
        String result = JSONObject.toJSONString(user);
        try {
            System.out.println(result);
            resp.getWriter().write(result);
        } catch (Exception e) {
            System.out.println("spotEdit方法跳转失败：");
            e.printStackTrace();
        }
    }

    /**
     * 分页查询
     * @param req
     * @param resp
     */
    public void pagernate(HttpServletRequest req, HttpServletResponse resp){
        //每页显示数据
        int pageSize = 10 ;
        //设定默认当前页码数
        int page = 1;
        //获取ajax发送的参数
        String getuserRole = req.getParameter("userRole");
        String getuserName = req.getParameter("userName");
        String getPage = req.getParameter("page");
        if(getPage !=null && ! "".equals(getPage)){
            page = (Integer.valueOf(getPage)) ;
        }
        //获取的参数创建user对象
        User user = new User();
        user.setUserName(getuserName);
        user.setUserRole(getuserRole);

        IUserService userService = new UserServiceImpl();
        Pager pager = userService.pagernate(page,pageSize,user);
        //将数据存储到session中，方便POI进行excel导出
        req.getSession().setAttribute("pager",pager);

        String result = JSONObject.toJSONString(pager);
        System.out.println("pagernate的result:"+result);

        try {
            resp.getWriter().write(result);
        } catch (Exception e) {
            System.out.println("pagernate方法跳转失败：");
            e.printStackTrace();
        }
    }
}
